﻿// <copyright file="DatabaseManager.cs" company="ThorIndustry">Copyright (c) ThorIndustry. All rights reserved.</copyright>

using System.Collections.Generic;

public class DatabaseManager : UnityEngine.MonoBehaviour, IDatatableService
{
    private Dictionary<System.Type, object> datatableByType = new Dictionary<System.Type, object>();
    
    public IDatatable<T> GetDatatable<T>(bool createIfNotExists = false) where T : IDatatableElement
    {
        if (this.datatableByType.ContainsKey(typeof(T)))
        {
            return this.datatableByType[typeof(T)] as IDatatable<T>;
        }
        
        // Try to create a datatable for the asked type...
        return null;
    }

    public void Register<T>(IDatatable<T> datatable) where T : IDatatableElement
    {
        if (this.datatableByType.ContainsKey(typeof(T)))
        {
            UnityEngine.Debug.LogError("A database already exists for type " + typeof(T).ToString() + ".");
            return;
        }

        this.datatableByType.Add(typeof(T), datatable);
    }
    
    protected virtual System.Collections.IEnumerator Start()
    {
        // Get all database.
        Database[] databases = this.gameObject.GetComponentsInChildren<Database>();

        // Register them.
        if (databases != null)
        {
            for (int index = 0; index < databases.Length; ++index)
            {
                this.CreateDatatable(databases[index]);
            }
        }

        // Provide the service.
        Services.Register<IDatatableService>(this);

        yield break;
    }

    private void CreateDatatable(Database database)
    {
        try
        {
            UnityEngine.Debug.Log("Try to load the database for type " + database.ElementType.ToString());

            // Create the datatable.
            System.Type openDatatableType = typeof(Datatable<>);
            System.Type genericDatatableType = openDatatableType.MakeGenericType(database.ElementType);

            object datatable = System.Activator.CreateInstance(genericDatatableType);
            if (datatable == null)
            {
                return;
            }

            // Load the text assets.
            IDatatableControl datatableControl = datatable as IDatatableControl;

            for (int index = 0; index < database.Files.Length; ++index)
            {
                datatableControl.LoadData(database.Files[index]);
            }

            this.datatableByType.Add(database.ElementType, datatable);
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.LogError("Exception while loading database data. ElementType = " + database.ElementType.ToString() + ". Exception = " + ex.ToString());
        }
    }
}